<template>
  <div>
    <el-upload
      class="upload-demo"
      :on-progress="handleFileUploadProgress"
      :headers="upload.headers"
      :action="upload.url"
      :on-success="handleFileSuccess"
      :on-remove="removeFiles"
      :before-upload="beforecheckfile"
      name="files"
      :data="{ batchId: batchId, businessType: 'FINANCE' }"
      :file-list="addform.fileList"
      :disabled="upload.isUploading"
      :show-file-list="false"
      accept=".rar,.zip,.doc,.docx,.pdf"
    >
      <el-button
        class="uploadBtn"
        icon="el-icon-upload"
        :disabled="upload.isUploading"
        >上传文件</el-button
      >
      <div slot="tip" class="el-upload__tip">
        支持扩展名：.rar .zip .doc .docx .pdf,大小不超过30M
      </div>
    </el-upload>
    <div
      v-for="(item, index) in addform.fileList"
      :key="index"
      style="
            width:400px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            color: #606266;
            padding-bottom: 0px;
          "
    >
      <span style="font-size: 12px"
        ><i class="el-icon-paperclip"></i> {{ item.fileName }}
      </span>
      <i
        class="el-icon-circle-close delicon"
        v-if="!fileList.length"
        @click="delfiledata(item.id, item.fileName,item.batchId)"
      ></i>
    </div>
    <el-input
      v-model.trim="addform.complaintfilelistvalidator"
      style="display: none"
    ></el-input>
  </div>
</template>

<script>
import { getToken } from "@/utils/util.js";
import { host } from "@/utils/config.js";
import { request } from "@/utils/request.js";

export default {
  props: {
    fileList: {
      type: Array,
      default: () => []
    }
  },
  watch: {
    fileList(val) {
      console.log('val', val)
      if(val.length>0){
        this.addform.fileList = val
      }
    }
  },
  mounted(){
    console.log('this.fileList123', this.fileList)
    if(this.fileList.length) {
      this.addform.fileList = this.fileList
    }
    
    
  },
  data() {
    return {
      addform: {
        fileList: [], //附件资料
        complaintfilelistvalidator: "",
        file: []
      },
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: getToken() },
        // 上传的地址
        url: host + "/system/file/upload"
      },
      batchId: "",
      addformrules: {}
    };
  },
  methods: {
    //删除后
    removeFiles(response, fileList) {
      let data = fileList;
      this.addComloaintsFiles(data);
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.open = true;
      this.upload.isUploading = true;
    },
    //上传附件前限制大小 格式
    beforecheckfile(file) {
      this.upload.open = true;
      this.upload.isUploading = true;
      let isfile = true;
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      let fileformat = ["rar", "zip", "doc", "docx", "pdf"];
      let fileSize = file.size / 1024 / 1024 
      const isLt10M = fileSize < 30;
      // 新增判断,判断文件总大小是否超过30MB
      let total = fileSize;
      console.log(this.addform.fileList)
      for(let i = 0;i < this.addform.fileList.length;i++){
        console.log(this.addform.fileList[i].fileSize)
        let fileSize = this.addform.fileList[i].fileSize
        // fileSize = fileSize.parseFloat();
        fileSize = parseFloat(fileSize.replace(/MB/ig,""))
        total += fileSize
      }
      console.log(total)
      isfile = fileformat.includes(String(testmsg));
      if (!isfile) {
        this.$message.error("上传文件格式不正确");
      }else if (total > 30 * 1024 * 1024) {
        if(!isLt10M){
          isfile = false;
          this.$message.error("上传文件大小不能超过 30M");
        }else{
          isfile = false;
          this.$message.error("上传文件总大小不能超过 30M");
        }
      }
      console.log("走过了这里")
      this.upload.open = false;
      this.upload.isUploading = false;
      return isfile;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      console.log("response",response)
      if (response.code == 200) {
        this.addform.file = response.data;
        this.batchId = response.data;
        this.getFileDataList(response.data);
        this.addComloaintsFiles(fileList);
      } else {
        this.$alert(response.msg, "上传文件", {});
      }
    },
    //诉求新增文件
    addComloaintsFiles(fileList) {
      if (fileList.length > 0) {
        this.addform.complaintfilelistvalidator = "yes";
      } else {
        this.addform.complaintfilelistvalidator = "";
      }
    },
    //删除文件
    async delfiledata(id, name, batchId) {
      let api = `${host}/system/file/${id}`;
      let res = await request(this, api, {}, "delete");
      if (res.code == 200) {
        this.$message({
          message: "删除" + name + "成功",
          type: "success"
        });
        this.getFileDataList(batchId);
      } else {
        this.$message.error(res.msg);
      }
    },
    //获取附件列表
    async getFileDataList(id) {
      let data = {
        batchId: id
      };
      let api = `${host}/system/file/list`;
      let res = await request(this, api, data, "GET");
      console.log(6666, res);
      if (res.code == 200) {
        this.addform.fileList = res.rows;
        this.$emit("changeUp", this.addform.fileList);
      } else {
        this.$message.error(res.msg);
      }
    }
  }
};
</script>

<style scoped>
.uploadBtn {
  background-color: #f1f2f4;
  color: #045db9;
  border-width: 0;
}
</style>
